package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.BulletinFileLogic;
import cn.topevery.garden.dal.logic.BulletinLogic;
import cn.topevery.garden.dal.logic.BulletinReadLogic;
import cn.topevery.garden.dal.logic.BulletinReceiveLogic;
import cn.topevery.garden.entity.dto.BulletinDTO;
import cn.topevery.garden.entity.dto.BulletinFileDTO;
import cn.topevery.garden.entity.dto.BulletinReceiveDTO;
import cn.topevery.garden.entity.po.BulletinFile;
import cn.topevery.garden.entity.po.BulletinRead;
import cn.topevery.garden.entity.po.BulletinReceive;
import cn.topevery.garden.entity.query.BulletinFileQuery;
import cn.topevery.garden.entity.query.BulletinQuery;
import cn.topevery.garden.entity.query.BulletinReadQuery;
import cn.topevery.garden.entity.query.BulletinReceiveQuery;
import cn.topevery.garden.entity.vo.BulletinFileVO;
import cn.topevery.garden.entity.vo.BulletinReadVO;
import cn.topevery.garden.entity.vo.BulletinReceiveVO;
import cn.topevery.garden.entity.vo.BulletinVO;
import cn.topevery.garden.entity.po.Bulletin;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.fetch.UserFetch;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.runtime.directive.contrib.For;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.dozermapper.core.Mapper;
import sun.swing.StringUIClientPropertyKey;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 
 */
@Api(tags = "")
@RestController
@RequestMapping("/bulletin")
public class BulletinController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    BulletinLogic bulletinLogic;

    @Autowired
    BulletinFileLogic bulletinFileLogic;
    @Autowired
    BulletinReceiveLogic receiveLogic;
    @Autowired
    BulletinReadLogic readLogic;

    @Autowired
    SysUserLogic userLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<BulletinVO>> listPage(@RequestBody BulletinQuery query) {
        return JsonResult.ok(bulletinLogic.listPage(query));
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody BulletinDTO dto) {
        if(StringUtils.isBlank(dto.getBulletinId())){
            dto.setBulletinId(UUID.randomUUID().toString());
            dto.setDate(LocalDateTime.now());
            dto.setUserName(getUserName());
        }
        if(ObjectUtils.isEmpty(dto.getLevel())){
            dto.setLevel(0);
        }
        if(ObjectUtils.isEmpty(dto.getOrderNum())){
            dto.setOrderNum(0);
        }
        bulletinLogic.saveOrUpdate(getUser().id.toString(),mapper.map(dto, Bulletin.class));
        BulletinFileQuery bulletinFileQuery = new BulletinFileQuery();
        bulletinFileQuery.setBulletinId(dto.getBulletinId());
        bulletinFileQuery.setPageIndex(1);
        bulletinFileQuery.setPageSize(100);
        DataPager<BulletinFileVO> bulletinFileVODataPager = bulletinFileLogic.listPage(bulletinFileQuery);
        for (BulletinFileVO vo : bulletinFileVODataPager.records){
            boolean present = dto.getFileList().stream()
                    .filter(n -> n.getFileId().equals(vo.getFileId()))
                    .findAny().isPresent();
            if(!present){
                BulletinFile file = mapper.map(vo, BulletinFile.class);
                file.setDbStatus(true);
                bulletinFileLogic.saveOrUpdate(getUser().id.toString(),file);
            }
        }

        if(ObjectUtils.isNotEmpty(dto.getFileList())){
            for (BulletinFileDTO fileDto : dto.getFileList()){
                boolean present = bulletinFileVODataPager.records.stream()
                        .filter(n -> n.getFileId().equals(fileDto.getFileId()))
                        .findAny().isPresent();
                if(!present) {
                    fileDto.setBulletinId(dto.getBulletinId());
                    if (ObjectUtils.isEmpty(fileDto.getDataType())) {
                        fileDto.setDataType((byte) 0);
                    }
                    bulletinFileLogic.saveOrUpdate(getUser().id.toString(), mapper.map(fileDto, BulletinFile.class));
                }
            }
        }
        List<BulletinRead> bulletinReads=new ArrayList<>();
        BulletinReceiveQuery query = new BulletinReceiveQuery();
        query.setBulletinId(dto.getBulletinId());
        query.setPageIndex(1);
        query.setPageSize(100);
        DataPager<BulletinReceiveVO> bulletinReceiveVODataPager = receiveLogic.listPage(query);

        for(BulletinReceiveVO vo : bulletinReceiveVODataPager.records){
            boolean present = dto.getReceiveDTOS().stream().filter(n -> n.getReceiveObjectId().equals(vo.getReceiveObjectId()) && n.getReceiveType().equals(vo.getReceiveType())).findAny().isPresent();
            if(!present){
                BulletinReceive receive = mapper.map(vo, BulletinReceive.class);
                receive.setDbStatus(true);
                receiveLogic.saveOrUpdate(getUser().id.toString(),receive);
            }
        }
        // 接收对象
        if(ObjectUtils.isNotEmpty(dto.getReceiveDTOS())){
            for(BulletinReceiveDTO receiveDTO : dto.getReceiveDTOS()){
                boolean present1 = bulletinReceiveVODataPager.records.stream()
                        .filter(n -> n.getReceiveObjectId().equals(receiveDTO.getReceiveObjectId()) && n.getReceiveType().equals(receiveDTO.getReceiveType()))
                        .findAny().isPresent();
                if(!present1) {
                    receiveDTO.setBulletinId(dto.getBulletinId());
                    //receiveDTO.setReceiveType(16003);
                    receiveLogic.saveOrUpdate(getUser().id.toString(), mapper.map(receiveDTO, BulletinReceive.class));
                }
                UserFetch fetch = new UserFetch();
                fetch.setDeptId(receiveDTO.getReceiveObjectId());
                List<SysUser> list = userLogic.getList(fetch);
                for(SysUser user: list){
                   boolean present = bulletinReads.stream().filter(m -> m.getUserId().equals(user.userId)).findAny().isPresent();
                   if(!present){
                       BulletinRead bulletinRead = new BulletinRead();
                       bulletinRead.setBulletinId(dto.getBulletinId());
                       bulletinRead.setReadStatus((short) 0);
                       bulletinRead.setUserId(user.userId);
                       bulletinRead.setUserName(user.userName);
                       bulletinReads.add(bulletinRead);
                   }
                }
            }
        }

        BulletinReadQuery query1 = new BulletinReadQuery();
        query1.setBulletinId(dto.getBulletinId());
        query1.setPageIndex(1);
        query1.setPageSize(10000);
        DataPager<BulletinReadVO> bulletinReadVODataPager = readLogic.listPage(query1);
        for(BulletinReadVO vo : bulletinReadVODataPager.records){
            boolean present = bulletinReads.stream()
                    .filter(n -> n.getUserId().equals(vo.getUserId()))
                    .findAny().isPresent();
            if(!present){
                BulletinRead read = mapper.map(vo, BulletinRead.class);
                read.setDbStatus(true);
                readLogic.saveOrUpdate(getUser().id.toString(),read);
            }
        }
        if(ObjectUtils.isNotEmpty(bulletinReads)){
            for (BulletinRead read:bulletinReads){
                boolean present = bulletinReadVODataPager.records.stream()
                        .filter(n -> n.getUserId().equals(read.getUserId()))
                        .findAny().isPresent();
                if(!present) {
                    readLogic.saveOrUpdate(getUser().id.toString(), read);
                }
            }
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult<BulletinVO> getInfoById(@RequestParam Integer id) {
        Bulletin entity = bulletinLogic.getEntity(id);
        BulletinVO vo= mapper.map(entity, BulletinVO.class);
        return JsonResult.ok(vo);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        bulletinLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(BulletinQuery query, HttpServletResponse response) {
        List<BulletinVO> list = bulletinLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", BulletinVO.class, "", response);
    }

}
